﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Qiang.QMath
{
    public class KdTree
    {

        public KdTree(int k)
        {
            if (k < 0)
            {
                // 出错，维度不能小于0
            }

            this._root = null;
        }


         
        private readonly int _k;  //点坐标的维度，是一维、二维 、三维或是几维

        private int _count;      //结点个数

        private KdNode _root;  //根结点


        /// <summary>
        /// 其实这才是kd树的构造方法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Insert(KdPoint key, object value)
        {
            //每次kd树插入新节点时都是从根节点开始插入，起始维度为0（即x）
            KdNode.Insert(key, value, this._root, 0, this._k);

            this._count++;
        }

        /// <summary>
        /// 查找某个节点的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object Search(KdPoint key)
        {
            KdNode node = KdNode.Search(key, this._root, this._k);

            return node == null ? null : node.value;

        }


        public object Nearest(KdPoint key)
        {
            return this.Nearest(key, 1)[0];
        }


        public object[] Nearest(KdPoint key, int num)
        {
            KdNeighbors neighbors = new KdNeighbors(num);
            KdNode.Nearest(this._root, key, null, double.MaxValue, 0, this._k,neighbors);

            return new object[1];
        }

    }
}
